const jwt = require('jsonwebtoken');
const { User } = require('../models'); // 从 models/index.js 导入已初始化的模型

// 生成 JWT Token
const generateToken = (userId) => {
    return jwt.sign({ userId }, process.env.JWT_SECRET, {
        expiresIn: process.env.JWT_EXPIRE
    });
};

// 用户注册
exports.register = async (req, res, next) => {
    try {
        const { username, email, password, firstName, lastName, phone } = req.body;

        // 创建用户
        const user = await User.create({
            username,
            email,
            password,
            firstName,
            lastName,
            phone
        });

        // 生成 token
        const token = generateToken(user.id);

        res.status(201).json({
            success: true,
            message: '注册成功',
            data: {
                token,
                user: {
                    id: user.id,
                    username: user.username,
                    email: user.email,
                    firstName: user.firstName,
                    lastName: user.lastName,
                    role: user.role
                }
            }
        });
    } catch (error) {
        next(error);
    }
};

// 用户登录
exports.login = async (req, res, next) => {
    try {
        const { email, password } = req.body;

        // 验证输入
        if (!email || !password) {
            return res.status(400).json({
                success: false,
                message: '请提供邮箱和密码'
            });
        }

        // 查找用户
        const user = await User.findOne({ where: { email } });

        if (!user || !(await user.comparePassword(password))) {
            return res.status(401).json({
                success: false,
                message: '邮箱或密码错误'
            });
        }

        // 更新最后登录时间
        await user.update({ lastLoginAt: new Date() });

        // 生成 token
        const token = generateToken(user.id);

        res.status(200).json({
            success: true,
            message: '登录成功',
            data: {
                token,
                user: {
                    id: user.id,
                    username: user.username,
                    email: user.email,
                    firstName: user.firstName,
                    lastName: user.lastName,
                    role: user.role
                }
            }
        });
    } catch (error) {
        next(error);
    }
};

// 获取当前用户信息
exports.getCurrentUser = async (req, res, next) => {
    try {
        const userId = req.user.id; // 假设通过中间件获取
        
        const user = await User.findByPk(userId);
        
        if (!user) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }
        
        res.status(200).json({
            success: true,
            data: user
        });
    } catch (error) {
        next(error);
    }
};

// 忘记密码
exports.forgotPassword = async (req, res, next) => {
    // 实现忘记密码逻辑
};

// 重置密码
exports.resetPassword = async (req, res, next) => {
    // 实现重置密码逻辑
};

// 更新用户资料
exports.updateProfile = async (req, res, next) => {
    try {
        const { firstName, lastName, phone } = req.body;
        
        const user = await User.findByPk(req.user.id);
        
        await user.update({
            firstName: firstName || user.firstName,
            lastName: lastName || user.lastName,
            phone: phone || user.phone
        });

        res.json({
            success: true,
            message: '资料更新成功',
            data: { user }
        });
    } catch (error) {
        next(error);
    }
};

// 修改密码
exports.changePassword = async (req, res, next) => {
    try {
        const { currentPassword, newPassword } = req.body;

        if (!currentPassword || !newPassword) {
            return res.status(400).json({
                success: false,
                message: '请提供当前密码和新密码'
            });
        }

        // 获取用户（包含密码）
        const user = await User.scope('withPassword').findByPk(req.user.id);

        // 验证当前密码
        const isValidPassword = await user.comparePassword(currentPassword);
        if (!isValidPassword) {
            return res.status(400).json({
                success: false,
                message: '当前密码错误'
            });
        }

        // 更新密码
        await user.update({ password: newPassword });

        res.json({
            success: true,
            message: '密码修改成功'
        });
    } catch (error) {
        next(error);
    }
};